package com.wkk.yuli.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.wkk.yuli.api.YuTemplate;
import com.wkk.yuli.bo.Disappear;
import com.wkk.yuli.core.Container;
import com.wkk.yuli.util.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;


/**
 * @author : WangKeKe
 * @date : 2020/9/24 13:51
 * Description : 接口实现类
 */
@Slf4j
@Service
public class YuTemplateImpl implements YuTemplate {


    @Override
    public void setObject(Object key, Object value) {
        // 调用该接口生命周期无限
        String jsonString = JSONObject.toJSONString(new Disappear(System.currentTimeMillis(), -1L, key, value));
        Container.getYuLi().put(key, jsonString);
    }

    @Override
    public void setObject(Object key, Object value, Integer seconds) {
        Long time = System.currentTimeMillis();
        String jsonString = JSONObject.toJSONString(new Disappear(time, time + seconds * 1000, key, value));
        Container.getYuLi().put(key, jsonString);
    }

    @Override
    public void setObjectNotExist(Object key, Object value, Integer seconds) {
        Long time = System.currentTimeMillis();
        String jsonString = JSONObject.toJSONString(new Disappear(time, time + seconds * 1000, key, value));
        Container.getYuLi().putIfAbsent(key, jsonString);
    }

    @Override
    public Boolean hasObject(Object key) {
        // - 存在 且 未过期 则返回true
        return Container.getYuLi().get(key) != null && ToolUtils.judgeDisappear(Container.getYuLi().get(key)) != null;
    }

    @Override
    public Object getObject(Object key) {
        // - 获取 - 判断是否过期 ，未过期则返回内容
        Object object = Container.getYuLi().get(key);
        return object != null ? ToolUtils.judgeDisappear(object) : null;

    }

    @Override
    public void removeObject(Object key) {
        Container.getYuLi().remove(key);
    }

    @Override
    public void clearAll() {
        for (Iterator<Map.Entry<Object, Object>> it = Container.getYuLi().entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<Object, Object> item = it.next();
            //判断逻辑
            it.remove();
        }
    }

    @Override
    public Integer getSize() {
        return Container.getYuLi().size();
    }

    @Override
    public Map<Object, Object> getAllKeyValue() {
        return Container.getYuLi();
    }
}
